﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.IO;
using DocFactoryWebLibrary;

namespace WebClientExample
{
    public partial class _Default : System.Web.UI.Page
    {
        private string mstrFileName = null;

        protected HtmlInputFile filMyFile;

        protected void Page_Load(object sender, EventArgs e)
        {
            bool blnFilePosted = fluUserTemplate.PostedFile != null;
            bool blnFileNameNotEmpty  = false;
            bool blnFileSmallEnough = false;

            if (blnFilePosted)
            {
               blnFileNameNotEmpty = fluUserTemplate.PostedFile.FileName != "";
               blnFileSmallEnough = fluUserTemplate.PostedFile.ContentLength < 51200;
            }

            if (!blnFileSmallEnough && blnFilePosted)
            {
                pnlError.Visible = true;
                lblErrorMessage.Text = "The maximum size of a template is 512kb.";
            }

            if (blnFilePosted && blnFileNameNotEmpty && blnFileSmallEnough)
            {
                // Get a reference to PostedFile object
                HttpPostedFile objUploadedFile = fluUserTemplate.PostedFile;

                // Get size of uploaded file
                int nFileLen = objUploadedFile.ContentLength;
                // Byte array the size of the uploaded file
                byte[] fileBytes = new byte[nFileLen];

                // Read uploaded file to the byte array
                objUploadedFile.InputStream.Read(fileBytes, 0, nFileLen);
                
                // Make a random file name 
                string strFileName = Request.PhysicalApplicationPath + "\\" + System.IO.Path.GetRandomFileName();
                
                // Write the file to the tempory file
                WriteToFile(strFileName, ref fileBytes);

                // Sucessful, write to the file name
                mstrFileName = strFileName;

            }

        }

        // Writes file to current folder
        private void WriteToFile(string strPath, ref byte[] Buffer)
        {
            // Create a file
            FileStream newFile = new FileStream(strPath, FileMode.Create);

            // Write data to the file
            newFile.Write(Buffer, 0, Buffer.Length);

            // Close file
            newFile.Close();
        }

        protected void butGenerate_Click(object sender, EventArgs e)
        {
            Dictionary<string, string> objPopulate = new Dictionary<string, string>();

            // Populdate the data from the onscreen form
            objPopulate.Add("<<TESTDATA0>>", txtField0.Text == "" ? "TestData0" : txtField0.Text);
            objPopulate.Add("<<TESTDATA1>>", txtField1.Text == "" ? "TestData1" : txtField1.Text);
            objPopulate.Add("<<TESTDATA2>>", txtField2.Text == "" ? "TestData2" : txtField2.Text);
            objPopulate.Add("<<TESTDATA3>>", txtField3.Text == "" ? "TestData3" : txtField3.Text);
            objPopulate.Add("<<TESTDATA4>>", txtField4.Text == "" ? "TestData4" : txtField4.Text);

            // DocumentServerWebLib
            WebTemplateParser objXMLParser = new WebTemplateParser();

            // Set the XMLParse with correct data.
            objXMLParser.MergeData(objPopulate);

            try
            {
                // The final name of the document produced
                string strRandomFileName = null;

                if (ddlTemplate.SelectedValue != "Upload File")
                {
                    // Predone XML template
                   objXMLParser.TemplateToRandomDocument(Request.PhysicalApplicationPath + "\\SampleTemplates\\Template1.xml",
                        Request.PhysicalApplicationPath + "TempDocs\\", out strRandomFileName);
                }
                else if (mstrFileName != null)
                {
                    // Custom XML template
                   objXMLParser.TemplateToRandomDocument(mstrFileName,
                        Request.PhysicalApplicationPath + "TempDocs\\", out strRandomFileName);
                   
                    // Clean up the uploaded file
                    System.IO.File.Delete(mstrFileName);
                }
                else
                {
                    pnlError.Visible = true;
                    lblErrorMessage.Text = "You must either select one of the existing templates or upload your own.";
                }

                if (pnlError.Visible == false)
                {
                    hlDownloadFile.NavigateUrl = "TempDocs/" + strRandomFileName;

                    pnlDownload.Visible = true;
                    pnlGenerate.Visible = false;
                }
                
            }
            catch (Exception Ex)
            {
                pnlError.Visible = true;
                lblErrorMessage.Text = Ex.Message;
            }
            finally
            {
                // Clean up
                objXMLParser = null;
            }
        }
    }
}
